#include "dialogimportcsv.h"
#include "ui_dialogimportcsv.h"
#include <QFileDialog>
#include <QTextStream>
#include <QMessageBox>

DialogImportCsv::DialogImportCsv(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DialogImportCsv)
{
    ui->setupUi(this);
    this->filename = QString();
}

DialogImportCsv::~DialogImportCsv()
{
    delete ui;
}


// Getters ====================================================================>

QString DialogImportCsv::getFileName() const
{
    return this->filename;
}

int DialogImportCsv::getStartingLine() const
{
    return ui->spinStartingLine->value();
}

QChar DialogImportCsv::getSeparatorChar() const
{
    return ui->lineSeparator->text().at(0);
}

QChar DialogImportCsv::getQuoteChar() const
{
    return ui->lineQuote->text().at(0);
}

bool DialogImportCsv::isFirstColumnNames() const
{
    return ui->checkNames->isChecked();
}


// Event Handlers =============================================================>

void DialogImportCsv::on_buttonBox_accepted()
{
    if (filename.isEmpty()) {
        QMessageBox::warning(this, "Empty file name",
                             "Cannot open a file without file name.",
                             QMessageBox::Ok);
        return;
    }
    else this->accept();
}

void DialogImportCsv::on_buttonBox_rejected()
{
    this->reject();
}

void DialogImportCsv::on_buttonBrowse_clicked()
{
    QFileDialog* dialog = new QFileDialog(this);
    dialog->setWindowTitle("Choose source file..");
    dialog->setFilter("Comma separated values (*.csv);;"
                      "Text files (*.txt);;"
                      "All files (*.*)");

    if (dialog->exec() == QDialog::Accepted) {
        // check if selected file exist and open it
        QFile* file = new QFile(dialog->selectedFiles().at(0));
        if (!file->exists() || !file->open(QFile::ReadOnly)) return;
        // create a text stream to read the file
        QTextStream* in = new QTextStream(file);
        // declare variables
        QString line;
        int line_number = 1;
        // preview first lines of the file
        ui->textEdit->clear();
        while (!in->atEnd() && line_number < PREVIEW_LINES) {
            line = "<b>" + QString::number(line_number) + ".</b> "
                    + in->readLine();
            ui->textEdit->append(line);
            line_number++;
        }
        if (line_number == PREVIEW_LINES)
            ui->textEdit->append("<b>...</b>");
        ui->textEdit->moveCursor(QTextCursor::Start);
        ui->textEdit->ensureCursorVisible();
        // update variables and dispose objects
        this->filename = file->fileName();
        ui->lineFileName->setText(QFileInfo(filename).fileName());
        file->close();
        delete in;
        delete file;
    }

    delete dialog;
}

